package com.pet_service.config;

import cn.hutool.json.JSONUtil;
import com.pet_service.result.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

//登录失败处理器
@Component //交给IOC容器管理
@Slf4j //日志
public class LoginFailureHandler implements AuthenticationFailureHandler {
    //登录失败,会调这个方法
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        //建议在控制台输出，方便调试
        // exception.printStackTrace();
        //把登录失败的原因传递给前端vue项目
        response.setContentType("application/json;charset=utf-8");
        //出现的异常信息
        String errorMessage=exception.getMessage();
        log.info("自定义认证失败处理器执行啦，失败原因{},{}",errorMessage,exception.getClass().getName());
        //封装传递给前端vue项目的对象
        Result r = Result.fail(500, errorMessage);
        //将对象转换成json格式字符串
        String jsonStr = JSONUtil.toJsonStr(r);
        //使用字符输出流传递数据
        response.getWriter().write(jsonStr);
    }
}
